<template>
  <div class="order">
    <div class="top">
      <div class="top_left">
        <selectTool
          :colmuns="headerConfig"
          :model-form="configData"
          @onFormChange="getOrderList"
        ></selectTool>
      </div>
      <div class="right">
        <el-button
          type="primary"
          @click="openDialog"
          v-permission="'order:saveOrUpdate'"
          >添加订单</el-button
        >
      </div>
    </div>
    <div class="content">
      <newTable
        :table-config="tableConfig"
        :table-data="tableList"
        :option-list="tableOptionList"
        :options="true"
        @clickBtn="go"
      ></newTable>
    </div>
    <div class="footer">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        @prev-click="prev"
        @change="sizeChange"
        @next-click="next"
      />
    </div>
  </div>

  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="650">
    <div style="padding: 10px">
      <el-form
        label-width="80px"
        :model="addData"
        :rules="addDataRules"
        ref="addDataRef"
      >
        <el-form-item label="订单名称" prop="name">
          <el-input
            :disabled="addType === 'permission' ? true : false"
            v-model="addData.name"
            placeholder="请输入订单名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="订单代码" prop="sn">
          <el-input
            :disabled="addType === 'permission' ? true : false"
            v-model="addData.sn"
            placeholder="请输入订单代码"
          ></el-input>
        </el-form-item>
        <el-form-item label="可选页面" prop="menuIds">
          <el-tree-select
            :disabled="addType === 'permission' ? true : false"
            v-model="addData.menuIds"
            :data="menuData"
            multiple
            :render-after-expand="false"
            show-checkbox
            check-strictly
            check-on-click-node
            placeholder="请选择可浏览页面"
          />
        </el-form-item>
      </el-form>
      <div style="display: flex; align-items: center; justify-content: center">
        <el-transfer
          v-model="permissionValue"
          :data="permissionList"
          filterable
          filter-placeholder="请输入权限名称"
          :titles="['可选权限', '已选权限']"
        />
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="add(addDataRef, permissionValue)">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {
  getOrderListApi,
  saveOrUpdateOrderApi,
  deleteOrderApi,
  getOrderByIdApi,
} from "@/api/orderApi";
import { onMounted, reactive, ref } from "vue";
import selectTool from "@/components/selectTool/index.vue";
import newTable from "@/components/newTable/index.vue";
import {
  headerConfig,
  configData,
  tableConfig,
  tableList,
  tableOptionList,
  addDataRules,
  addDataRef,
  permissionList,
  permissionValue,
} from "./config";
import { ElMessage, type FormInstance } from "element-plus";
import { convertToTreeData } from "@/utils/routeGenerator";

/**
 * @description 添加部门弹窗
 */
const dialogVisible = ref(false);

const dialogTitle = ref("添加订单");

const addType = ref("");

/**
 * @description 打开添加部门弹窗
 */
const openDialog = () => {
  dialogVisible.value = true;
  dialogTitle.value = "添加订单";
  addData.id = "";
  addData.name = "";
  addData.sn = "";
  addData.menuIds = [];
  addType.value = "add";
  getAllPermission();
  permissionValue.value = [];
};

/**
 * @description 表格操作
 */
const go = (item: any, option: String) => {
  // console.log(item, option);
  switch (option) {
    case "delete":
      del(item.row.id);
      break;
    case "info":
      getOrderById(item.row);
      break;
    case "permission":
      permissionOrder(item.row);
      break;
    default:
      break;
  }
};

/**
 * @description 添加部门数据
 */
const addData = reactive({
  id: "",
  name: "",
  sn: "",
  menuIds: [],
});

/**
 * @description 添加订单
 */
const add = async (formEl: FormInstance | undefined, data?: any) => {
  // console.log("ceshi", addData);

  if (!formEl) return;
  if (addType.value === "permission") {
    dialogVisible.value = false;
    return;
  }
  await formEl.validate((valid, fields) => {
    if (valid) {
      const newAddData = {
        order: {
          ...addData,
        },
        permissionIds: data,
        menuIds: addData.menuIds,
      };
      saveOrUpdateOrderApi(newAddData).then((res: any) => {
        dialogVisible.value = false;
        getOrderList();
        formEl.resetFields();
        if (addType.value === "edit") {
          ElMessage.success("修改成功");
        } else {
          ElMessage.success("添加成功");
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

/**
 * @description 编辑订单
 */
const getOrderById = (item: any) => {
  console.log("编辑", item);
  dialogTitle.value = "编辑订单";
  addType.value = "info";
  dialogVisible.value = true;
  addData.id = item.order_id;
  addData.name = item.name;
  addData.sn = item.sn;
  getOrderByIdApi(item.order_id);
};

const permissionOrder = (item: any) => {
  dialogTitle.value = "查看权限";
  dialogVisible.value = true;
  addType.value = "permission";
  addData.id = item.id;
  addData.name = item.name;
  addData.sn = item.sn;
  getAllPermission();
  getOrderAuthority(item.id);
  getMenuByOrderId(item.id);
};

/**
 * @description 删除订单
 */
const del = (id: number) => {
  // console.log("删除", id);

  deleteOrderApi(id).then((res: any) => {
    // console.log(res);
    getOrderList();
    ElMessage.success("删除成功");
  });
};

/**
 * @description 获取订单权限
 */
const getOrderAuthority = (id: number) => {
  getOrderByIdApi(id).then((res: any) => {
    // console.log("测试", res);
    permissionValue.value = res.data.map((item: any) => item.id);
  });
};

/**
 * 订单总条数
 */
const total = ref(0);

const pageNum = ref(1);

const pageSize = ref(10);

/**
 * @description 获取订单列表
 */
const getOrderList = () => {
  getOrderListApi({
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    order_id: configData.value.orderId,
    courier: configData.value.courier,
    initiator: configData.value.initiator,
    orderStatus: configData.value.orderStatus,
  }).then((res: any) => {
    console.log(res);
    tableList.value = res.data.list;
    total.value = res.data.total;
  });
};

/**
 * @description 上一页
 */
const prev = () => {
  console.log("上一页");
  getOrderListApi({
    pageNum: pageNum.value - 1,
    pageSize: 10,
  }).then((res: any) => {
    // console.log(res);
    tableList.value = res.data.list;
    total.value = res.data.total;
  });
};

/**
 * @description 下一页
 */
const next = () => {
  console.log("下一页");
  getOrderListApi({
    pageNum: pageNum.value + 1,
    pageSize: 10,
  }).then((res: any) => {
    // console.log(res);
    tableList.value = res.data.list;
    total.value = res.data.total;
  });
};

/**
 * @description 每页显示条数
 */
const sizeChange = (val: number) => {
  console.log(val);
  pageNum.value = val;
  getOrderListApi({
    pageNum: pageNum.value,
    pageSize: 10,
  }).then((res: any) => {
    // console.log(res);
    tableList.value = res.data.list;
    total.value = res.data.total;
  });
};

const getAllPermission = () => {
  // console.log("获取权限", addType.value);
  permissionList.value = JSON.parse(
    localStorage.getItem("permission") || "[]"
  ).map((item: any) => {
    return {
      key: item.id,
      label: item.name,
      disabled: addType.value === "permission" ? item.id : false,
    };
  });
  // console.log("permissionList", permissionList.value);
};

// 菜单列表
const menuData = ref([]);

// 获取全部菜单权限
const getAllMenu = () => {
  // const arr = convertToTreeData(
  //   JSON.parse(localStorage.getItem("menuList") || "[]")
  // );
  // // console.log("全部菜单", arr);
  // menuData.value = arr;
};

// 获取订单菜单权限
const getMenuByOrderId = (id: number) => {
  // getOrderMenuListApi(id).then((res) => {
  //   // console.log("菜单权限", res);
  //   addData.menuIds = res.data.map((i: any) => i.menu_id + "");
  //   // console.log("ew", addData.menuIds);
  // });
};

onMounted(() => {
  getOrderList();
  getAllPermission();
  getAllMenu();
});
</script>

<style>
.order {
  display: flex;
  flex-direction: column;
  height: 100%;
  border-radius: 15px;
}

.top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
  padding: 0 20px 0 0;
  background-color: rgb(255, 255, 255);
  border-radius: 15px;
  box-shadow: 1px 1px 5px 1px rgba(0, 0, 0, 0.1); /* 阴影 */
  margin-bottom: 10px;
  flex: 0 0 auto;
}

.content {
  height: 100%;
  display: flex;
  background-color: rgb(255, 255, 255);
  border-radius: 15px;
  box-shadow: 1px 1px 5px 1px rgba(0, 0, 0, 0.1); /* 阴影 */
  flex: 1 1 auto;
  overflow: auto;
  padding: 10px;
}

.footer {
  display: flex;
  justify-content: center;
  margin-top: 10px;
  background-color: rgb(255, 255, 255);
  border-radius: 15px;
  box-shadow: 1px 1px 5px 1px rgba(0, 0, 0, 0.1); /* 阴影 */
  height: 60px;
  flex: 0 0 auto;
}
</style>
